import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    ListView,
    TouchableOpacity,
    FlatList,
    StatusBar,
    AsyncStorage,
    Platform
} from 'react-native';
import Config from '../common/Config'
import Utils from '../common/Utils'
import {Toast,ModalIndicator} from 'teaset';
const STORAGE_KEY_TOKEN = '@AsyncStorageDemo:key_token';
const {height, width} = Dimensions.get('window');
export default class NewsTabPage extends Component {
    componentWillMount() {
        this._loadInitialState().done();
    }
    async _loadInitialState(){
        try{
            let value=await AsyncStorage.getItem(STORAGE_KEY_TOKEN);
            if(value!==null){
                this._appendMessage(value);
            }else{
                this._appendMessage('');
            }
        }catch(error){
            this._appendMessage('AsyncStorage错误'+error.message);
        }
    }
    _appendMessage=(message)=>{
        this.setState({
            token:this.state.token.concat(message)
        },()=>this.getInfo());
    };
    getInfo=()=>{
        let params={
            "token":this.state.token
        }
        ModalIndicator.show("正在请求数据......");
        fetch(Config.baseApi+'/IM/selectMessageList',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                ModalIndicator.hide();
                if(responseJson.status!==1){
                    this.setState({
                        recentConversation:responseJson.data,
                        numberMax:responseJson.data.length
                    })
                }else{
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                ModalIndicator.hide();
                Toast.message(error);
            });
    };
    constructor(props) {
        super(props);
        this.state = {
            isShow:false,
            recentConversation: [],
            token:'',
            numberMax:'',
        };
    };
    goToPage=(page)=>{
        this.setState({
            isShow:false
        },()=>{
            Actions.push(page)
        })
    };

    render() {
        return (
            <View style={styles.container}>
                <StatusBar
                    backgroundColor="black"
                    barStyle="light-content"
                />
                {this.state.isShow
                ?(<TouchableOpacity
                        onPress={()=>this.setState({
                            isShow:false
                        })}
                        style={{position: 'absolute',top:0,bottom:0,left:0,right:0,
                            backgroundColor:'rgba(0,0,0,0)',zIndex:2}}>
                        <View style={styles.showView}>
                            <View style={{flexDirection:'row'}}>
                                <View style={styles.triangleLeft}/>
                                <View style={styles.triangleRight}/>
                            </View>
                            <View style={{backgroundColor:'#000000',width:110,height:69,borderRadius:5}}>
                                <TouchableOpacity
                                    onPress={()=>this.goToPage('QueryFriendsPage')}
                                    style={{alignItems:'center',flexDirection:'row',height:34,width:110}}>
                                    <Image
                                        source={ImageUtil.Upload}
                                        style={{marginLeft:14,height:18,width:18}}/>
                                    <Text style={{fontSize:14,marginLeft:12,color:'#ffffff'}}>添加好友</Text>
                                </TouchableOpacity>
                                <View style={{height:1,width:100,backgroundColor:'#ffffff',marginLeft:5}}/>
                                <TouchableOpacity
                                    onPress={()=>this.goToPage()}
                                    style={{ alignItems:'center',flexDirection:'row',height:34,width:110}}>
                                    <Image
                                        source={ImageUtil.AddLending}
                                        style={{marginLeft:14,height:18,width:18}}/>
                                    <Text style={{fontSize:14,marginLeft:12,color:'#ffffff'}}>发起群聊</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </TouchableOpacity>)
                :(null)}
                <View style={styles.titleView}>
                    <Text style={styles.titleMsg}>消息</Text>
                    <TouchableOpacity
                        onPress={()=>this.setState({
                            isShow:true
                        })}
                        style={styles.titleImgView}>
                        <Image
                            style={styles.titleImg}
                            source={ImageUtil.adjunctionWhite}/>
                    </TouchableOpacity>
                </View>
                <FlatList
                    ListHeaderComponent={this.headList}
                    ItemSeparatorComponent={this.middleLabel}
                    data={this.state.recentConversation}
                    renderItem={this.renderItem}
                    keyExtractor={this._keyExtractor}
                />
            </View>
        );
    }

    headList=()=>{
        return(
            <View>
                <TouchableOpacity style={styles.labelChangeView}>
                    <Image
                        style={styles.labelImg}
                        source={ImageUtil.CustomerService}/>
                    <Text style={{marginLeft:15,fontSize:14, color:'#000000',justifyContent:'center'}}>信用客服0574</Text>
                </TouchableOpacity>
                <TouchableOpacity
                    // onPress={()=>Actions.ChatMessagesPage()}
                    style={styles.labelChangeView}>
                    <Image
                        source={ImageUtil.CustomerService}
                        style={{height:44,width:44,marginLeft:15,borderRadius:5,marginTop:23/2,marginBottom:23/2}}/>
                    <View style={{marginLeft:14}}>
                        <Text style={{fontSize:16,color:'#000000'}}>0574区域聊天室</Text>
                        <Text style={{fontSize:14,color:'#646464',marginTop:11}}>慈溪区域聊天室</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    };


    middleLabel=()=>{
        return(
            <View style={{height:1,width:width,backgroundColor:'#ffffff'}}>
                <View style={{height:1,backgroundColor:'#e3e3e4',width:width-30,marginLeft:15}}/>
            </View>
        )
    };

    renderItem=(item)=>{
        let nickname='';
        if(item.item.remarkName!==''&&item.item.remarkName!==null){
            nickname=item.item.remarkName
        }else {
            nickname=item.item.nickName
        }
        return(
            <View>
                {item.index==0
                    ?(<View style={{height:1,width:width,backgroundColor:'#e3e3e4',marginTop:5}}/>)
                    :null}
                <TouchableOpacity
                    onPress={()=>Actions.ChatMessagesPage({toClientId:item.item.toClientId,nickname:nickname,
                        avatar:"http://106.14.209.177/upload/"+item.item.head})}
                    style={[styles.labelChangeView,{borderBottomWidth:0,borderTopWidth:0,marginTop:0}]}>
                    <Image
                        source={{uri:"http://106.14.209.177/upload/"+item.item.head}}
                        style={{height:44,width:44,marginLeft:15,borderRadius:5,backgroundColor:'#f0f0f0',marginTop:23/2,marginBottom:23/2}}/>
                    <View style={{marginLeft:14}}>
                        <Text style={{fontSize:16,color:'#000000'}}>{nickname}</Text>
                        <Text style={{fontSize:14,color:'#646464',marginTop:11}}>{item.item.message}</Text>
                    </View>
                    <View style={styles.TimeView}>
                        <Text style={styles.TimeMsg}>{item.item.timeFomat}</Text>
                    </View>
                </TouchableOpacity>
                {item.index==this.state.numberMax-1
                ?(<View style={{height:1,width:width,backgroundColor:'#e3e3e4'}}/>)
                :(null)}
            </View>
        )
    };

    _keyExtractor = (item, index) => index;

    // renderItem = (data) => {
        // let lastTime = data.item.lastTime;
        // let lastMsg = data.item.messages[data.item.messages.length - 1];
        // let contactId = lastMsg.from;
        // if (contactId == this.state.username) {
        //     contactId = lastMsg.to;
        // }
        // let nick = data.item.nick;
        // // if (Utils.isEmpty(nick)) {
        // //     nick = contactId;
        // // }
        // let params={
        //     "token":this.state.token,
        //     "coverId":contactId
        // };
        // fetch(Config.baseApi+'/directories/getInfo',{
        //     method: 'POST',
        //     headers: {
        //         'Content-Type': 'application/x-www-form-urlencoded',
        //     },
        //     body: Utils.getParamsString(params)
        // })
        //     .then((response) => response.json())
        //     .then((responseJson) => {
        //         ModalIndicator.hide();
        //         if(responseJson.status===0){
        //             if(responseJson.data.remarkVO===null) {
        //                 nick=responseJson.data.nickname
        //             }else {
        //                 if(responseJson.data.remarkVO.name===null||responseJson.data.remarkVO.name==''){
        //                     nick=responseJson.data.nickname
        //                 }else {
        //                     nick=responseJson.data.remarkVO.name
        //                 }
        //             }
        //         }else{
        //             Toast.message(responseJson.msg);
        //         }
        //     })
        //     .catch((error) => {
        //         Toast.message(error);
        //     });
        // let lastMsgContent = '';
        // if (lastMsg.msgType == 'txt') {
        //     lastMsgContent = lastMsg.data;
        // } else if (lastMsg.msgType == 'img') {
        //     lastMsgContent = '[图片]';
        // }
        // let avatar = require('../image/ic_list_icon.png');
        // if (data.item.avatar != null) {
        //     avatar = {uri: data.item.avatar};
        // }
        // return (
        //     <View>
        //         <TouchableOpacity
        //             // onPress={()=>Actions.ChatMessagesPage({contactId:contactId,name:nick,avatar:avatar})}
        //             style={styles.labelChangeView}>
        //             <Image style={{height:44,width:44,marginLeft:15,borderRadius:5,backgroundColor:'#f0f0f0',marginTop:23/2,marginBottom:23/2}}/>
        //             <View style={{marginLeft:14}}>
        //                 <Text style={{fontSize:16,color:'#000000'}}>{nick}</Text>
        //                 <Text style={{fontSize:14,color:'#646464',marginTop:11}}>{TimeUtil.formatChatTime(lastTime)}</Text>
        //             </View>
        //             <View style={styles.listItemSubContainer}>
        //                 <Text numberOfLines={1} style={styles.listItemSubtitle}>{lastMsgContent}</Text>
        //                 {
        //                     data.item.unreadCount > 0 ? (
        //                         <View style={styles.redDot}>
        //                             <Text style={styles.redDotText}>{data.item.unreadCount}</Text>
        //                         </View>
        //                     ) : ( null )
        //                 }
        //             </View>
        //         </TouchableOpacity>
        //         <View style={styles.divider}/>
        //     </View>
        // );
    // }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor:'#f0f0f0'
    },
    titleView:{
        backgroundColor:'#000000',
        width:width,
        alignItems:'center',
        justifyContent:'center',
        height:Platform.OS==='ios'?64:44
    },
    titleMsg:{
        textAlign:'center',
        fontSize:20,
        color:'#ffffff',
        marginTop:Platform.OS==='ios'?34:14,
        marginBottom:29/2
    },
    titleImgView:{
        position: 'absolute',
        right:15, bottom:25/2,
    },
    labelView:{
        height:45,
        width:width,
        backgroundColor:'#ffffff',
        borderBottomWidth:1,
        borderTopWidth:1,
        borderColor:'#e3e3e4',
        marginTop:5,
        flexDirection:'row',
        alignItems:'center'
    },
    labelChangeView:{
        width:width,
        backgroundColor:'#ffffff',
        borderBottomWidth:1,
        borderTopWidth:1,
        borderColor:'#e3e3e4',
        marginTop:5,
        alignItems:'center',
        flexDirection:'row'
    },
    labelImg:{
        marginLeft:15,
        width:44,
        height:44,
        borderRadius:5,
        marginTop:23/2,marginBottom:23/2
    },
    labelMsg:{
        marginLeft:19,
        fontSize:14,
        color:'#000000'
    },
    showView:{
        position: 'absolute',
        top:Platform.OS==='ios'?68:45,right:15,zIndex:5,
        width:110,
        borderRadius:5,
        opacity:1
    },
    triangleLeft:{
        width: 0,
        height: 0,
        backgroundColor: 'rgba(0,0,0,0)',
        borderStyle: 'solid',
        borderLeftWidth: 6,
        borderRightWidth: 6,
        borderBottomWidth: 8,
        borderTopWidth: 8,
        borderLeftColor: 'transparent',
        borderRightColor: '#000000',
        borderTopColor: 'transparent',
        borderBottomColor: '#000000',
        marginLeft:80
    },
    triangleRight:{
        width: 0,
        height: 0,
        backgroundColor: 'rgba(0,0,0,0)',
        borderStyle: 'solid',
        borderLeftWidth: 6,
        borderRightWidth: 6,
        borderBottomWidth: 8,
        borderTopWidth: 8,
        borderLeftColor: '#000000',
        borderRightColor: 'transparent',
        borderTopColor: 'transparent',
        borderBottomColor: '#000000',
    },
    listItemSubContainer: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    listItemSubtitle: {
        color: '#999999',
        fontSize: 14,
        marginTop: 3,
        flex: 1,
    },
    redDot: {
        borderRadius: 90,
        width: 18,
        height: 18,
        backgroundColor: '#FF0000',
        justifyContent: 'center',
        alignItems: 'center'
    },
    redDotText: {
        color: '#FFFFFF',
        fontSize: 14,
    },
    TimeView:{
        position: 'absolute',
        right:15,top:15,
    },
    TimeMsg:{
        fontSize:14,
        color:'#646464'
    }
});
